package xml.pull_xml_api;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.xml.namespace.QName;
import javax.xml.stream.Location;

import com.google.common.collect.Maps;


public class StartTag extends Event {
	
	private final QName name;
	private final Map<QName, String> attrsMap;
	private final List<Attr> attrs;

	public StartTag(QName name, List<Attr> attrs) {
		super(null);
		this.name = name;
		this.attrs = attrs;
		this.attrsMap = createAttrsMap(attrs);
	}
	
	StartTag(QName name, List<Attr> attrs, Location location) {
		super(location);
		this.name = name;
		this.attrs = attrs;
		this.attrsMap = createAttrsMap(attrs);
	}
	
	private Map<QName, String> createAttrsMap(List<Attr> attrs) {
		Map<QName, String> res = Maps.newHashMap();
		for (Attr attr: attrs) {
			res.put(attr.getName(), attr.getValue());
		}
		return res;
	}
	
	public StartTag(QName name, Attr... attrs) {
		this(name, Arrays.asList(attrs));
	}
	
	public StartTag(String localName, Attr... attrs) {
		this(new QName(localName), attrs);
	}
	
	public StartTag(String nsUri, String localPart, Attr... attrs) {
		this(new QName(nsUri, localPart), attrs);
	}

	public QName getName() {
		return name;
	}

	public List<Attr> getAttrs() {
		return attrs;
	}
	
	public String getAttrValue(String name) {
		return getAttrValue(new QName(name));
	}

	private String getAttrValue(QName qName) {
		return attrsMap.get(qName);
	}

	@Override
	public boolean isChars() {
		return false;
	}

	@Override
	public boolean isStartDoc() {
		return false;
	}

	@Override
	public boolean isEndDoc() {
		return false;
	}

	@Override
	public boolean isStartTag() {
		return true;
	}

	@Override
	public boolean isEndTag() {
		return false;
	}
	
	public boolean matches(String localPart, Attr... attrs) {
		return this.matches(new QName(localPart), attrs);
	}
	
	public boolean matches(String nsURI, String localPart, Attr... attrs) {
		return this.matches(new QName(nsURI, localPart), attrs);
	}
	
	public boolean matches(Attr... attrs) {
		return this.matches((QName) null, attrs);
	}

	public boolean matches(QName name, Attr... attrs) {
		return (name == null || this.name.equals(name)) && matchesAttrs(attrs);
	}

	private boolean matchesAttrs(Attr[] attrs) {
		for (Attr attr: attrs) {
			String myValue = getAttrValue(attr.getName());
			if (myValue == null || !myValue.equals(attr.getValue()))
				return false;
		}
		return true;
	}
}
